package zhoug.player.qly;

import android.view.View;
import android.view.ViewGroup;

import com.cmcc.qlyopensdk.player.OnAudioCallListener;
import com.cmcc.qlyopensdk.player.OnPlayerListener;
import com.cmcc.qlyopensdk.player.constant.AudioState;
import com.cmcc.qlyopensdk.player.constant.PlayStatus;
import com.cmcc.qlyopensdk.player.impl.QlyOpenSdkPlayer;

import zhoug.common.utils.ThreadUtils;
import zhoug.logging.Logger;
import zhoug.player.core.BasePlayer;
import zhoug.player.core.Callback;
import zhoug.player.core.CameraAbility;
import zhoug.player.core.CameraSetting;
import zhoug.player.core.OnCameraAbilityCallback;
import zhoug.player.core.OnCameraSettingCallback;
import zhoug.player.core.OnTalkListener;
import zhoug.player.core.PlayError;
import zhoug.player.core.PlayerSDK2;
import zhoug.player.core.RecordSegment;
import zhoug.player.core.ZPlayer;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * @Author: zhoug
 * @Date: 2024-12-09
 * @Description:
 */
public class QlyPlayerHelper extends BasePlayer {
    private static final String TAG = ">>>QlyPlayerHelper";
    private static final boolean DEBUG = PlayerSDK2.isDebug();
    private QlyOpenSdkPlayer mPlayer;
    protected boolean isTalking = false;
    private boolean isConnect = false;//是否连接设备

    /**
     * 初始化播放器
     */
    public void initPlayer() {
        if (DEBUG)
            Logger.d(TAG, "initPlayer:初始化千里眼播放器");
        mPlayer = new QlyOpenSdkPlayer(mContext, getMacByDeviceId());
        mPlayer.setMediaCodecEnabled(true); //设置是否硬解，默认true
        mPlayer.setOnPlayerListener(new OnPlayerListener() {
            @Override
            public void onStateChanged(int state, int code) {
                switch (state) {
                    case PlayStatus.STATE_IDLE://空闲
                        callStatusChange(ZPlayer.STATE_IDLE);
                        break;
                    case PlayStatus.STATE_PREPARING://资源准备

                        break;
                    case PlayStatus.STATE_PREPARED://资源准备好了
                        callStatusChange(ZPlayer.STATE_PREPARED);
                        break;
                    case PlayStatus.STATE_BUFFERING://缓冲

                        break;
                    case PlayStatus.STATE_BUFFERED://缓冲完成

                        break;
                    case PlayStatus.STATE_PLAYING://播放
                        setMute();
                        callStatusChange(ZPlayer.STATE_PLAYING);
                        break;
                    case PlayStatus.STATE_PAUSED://暂停
                        callStatusChange(ZPlayer.STATE_PAUSE);
                        break;
                    case PlayStatus.STATE_STOPED://停止
                        callStatusChange(ZPlayer.STATE_IDLE);
                        break;
                    case PlayStatus.STATE_COMPLETED://播放完成
                        callStatusChange(ZPlayer.STATE_ENDED);
                        break;
                    case PlayStatus.STATE_CONTROL_ERROR://控制错误
                        callError(PlayError.UNKNOWN_ERROR, "控制错误");
                        break;
                    case PlayStatus.STATE_ERROR://错误
                        callError(PlayError.UNKNOWN_ERROR, "错误代码:" + code);
                        break;
                }
            }

            /**
             * 当视频开始播放时回调视频真实尺寸
             * @param width
             * @param height
             */
            @Override
            public void onVideoSizeChanged(int width, int height) {
                if (mOnPlayListener != null) {
                    ThreadUtils.runMainThread(() -> mOnPlayListener.onVideoSizeChanged(width, height));
                }
            }

            /**
             *
             * 播放完成
             */
            @Override
            public void onPlaybackComplete() {
                if (DEBUG)
                    Logger.d(TAG, "onPlaybackComplete:播放完成");
                callStatusChange(ZPlayer.STATE_ENDED);
            }
        });
        //对讲监听
        mPlayer.setOnOnAudioCallListener(onAudioCallListener);

        View playerView = mPlayer.getPlayerView();
        if (mPlayViewGroup != null) {
            mPlayViewGroup.removeAllViews();
            mPlayViewGroup.addView(playerView);
        }
    }


    private final OnAudioCallListener onAudioCallListener = new OnAudioCallListener() {
        @Override
        public void onAudioStateChanged(int state) {
            switch (state) {
                case AudioState.AUDIO_STATE_AVAILABLE://可进行通话
                    if (DEBUG)
                        Logger.d(TAG, "可进行通话:");
                    break;
                case AudioState.AUDIO_STATE_UNAVAILABLE://不可进行通话
                    Logger.e(TAG, "不可进行通话:");
                    if (isTalking) {
                        callTalking(OnTalkListener.FAILED, "不可进行通话");
                        stopVoiceTalk();
                    }
                    break;
                case AudioState.AUDIO_STATE_ERROR_BUSY://别人正在通话导致断开
                    Logger.e(TAG, "别人正在通话导致断开");
                    if (isTalking) {
                        callTalking(OnTalkListener.EXCEPTION, "别人正在通话导致断开");
                        stopVoiceTalk();
                    }
                    break;
                case AudioState.AUDIO_STATE_ERROR_STOP://通话异常断开
                    Logger.e(TAG, "通话异常断开:");
                    if (isTalking) {
                        callTalking(OnTalkListener.EXCEPTION, "通话异常断开");
                        stopVoiceTalk();
                    }
                    break;
            }
        }
    };

    /**
     * 连接设备
     *
     * @param callback
     */
    protected void connect(@NonNull Callback<String> callback) {
        if (DEBUG)
            Logger.d(TAG, "connect:连接设备:" + mPlayUrl);
        QlySdk.connectCamera(mContext, getMacByDeviceId(), callback);
    }

    /**
     * 开始播放,每次都是重新加载资源播放,可以播放新的url
     */
    @Override
    public void startPlay() {
        callStatusChange(ZPlayer.STATE_START);
        if (isConnect) {
            if (mPlayer == null) {
                initPlayer();
                start();
            } else {
                if (mPlayState == ZPlayer.STATE_PAUSE) {
                    resumePlay();
                } else {
                    start();
                }
            }
        } else {
            connect(new Callback<String>() {
                @Override
                public void onSuccess(String s) {
                    isConnect = true;
                    if (mAutoGetAbility) {
                        getDeviceAbility();
                    }
                    if (mAutoGetSettings) {
                        getCameraSettings();
                    }
                    if (mPlayer == null) {
                        initPlayer();
                    }
                    start();
                }

                @Override
                public void onError(int status, String error) {
                    isConnect = false;
                    callError(status, error);

                }
            });
        }
    }

    private void start() {
        if (mPlayer != null) {
            try {
                mPlayer.prepare();
                mPlayer.start();
            } catch (Exception e) {
                callError(PlayError.UNKNOWN_ERROR, e.getMessage());
            }
            setMute();
        }
    }

    /**
     * 停止播放,会释放加载的媒体和资源
     */
    @Override
    public void stopPlay() {
        pausePlay();
    }

    /**
     * 如果正在播放则暂停播放,否则调用{@link #stopPlay()}停止播放
     */
    @Override
    public void pausePlay() {
        if (mPlayer != null) {
            callStatusChange(ZPlayer.STATE_PAUSE);
            mPlayer.pause();
        }
    }

    /**
     * 如果暂停了或者资源已经准备好了则播放,否则{@link #startPlay()}重新开始播放
     */
    @Override
    public void resumePlay() {
        if (mPlayer != null) {
            mPlayer.resume();
        }
    }

    /**
     * 切换为直播
     */
    public void switchToLive() {
        if (mPlayer != null) {
            mPlayer.switchToLive();
        }
    }

    /**
     * 高标清切换
     */
    public void switchPlayQuality(@NonNull Callback<Integer> callback) {
        if (mCameraSetting == null) return;
        int hd = mCameraSetting.getQualityVideo() == ZPlayer.QUALITY_HD ? ZPlayer.QUALITY_SD : ZPlayer.QUALITY_HD;
        QlySdk.switchPlaybackQuality(getMacByDeviceId(), hd, new Callback<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                if (integer != null && mCameraSetting != null) {
                    mCameraSetting.setQualityVideo(hd);
                }
                callback.onSuccess(integer);
            }

            @Override
            public void onError(int code, String error) {
                callback.onError(PlayError.UNKNOWN_ERROR, error);
            }
        });
    }

    /**
     * 获取云存储回放数据列表
     *
     * @param startTime
     * @param endTime
     * @param callback
     */
    public void getTimelineSectionList(long startTime, long endTime, @NonNull Callback<List<RecordSegment>> callback) {
        QlySdk.getTimelineSectionList(getMacByDeviceId(), startTime, endTime, callback);
    }

    /**
     * 设置指定位置播放
     *
     * @param positionMs 毫秒
     */
    @Override
    public void seekTo(long positionMs) {
        if (mPlayer != null) {
            mPlayer.seek(positionMs);
        }
    }

    @Override
    public void release() {
        mCameraAbility = null;
        mCameraSetting = null;
        callStatusChange(ZPlayer.STATE_IDLE);
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
        if (isConnect) {
            QlySdk.disconnect();
            isConnect = false;
        }
        super.release();
    }

    /**
     * 开始录制视频
     *
     * @param path 保存的视频地址,不一定使用
     */
    @Override
    public void startRecordVideo(String path) {

    }

    /**
     * 停止录制视频
     */
    @Override
    public void stopRecordVideo() {

    }

    /**
     * 开启对讲
     */
    @Override
    public void startVoiceTalk() {
        if (mPlayer != null) {
            isTalking = true;
            if (isMute()) {
                setMute(false);
            }
            callTalking(OnTalkListener.SUCCESS, "正在开启对讲");
            mPlayer.startAudio(mCameraAbility != null && mCameraAbility.isSupportDuplexAudioTalk());
        }
    }

    /**
     * 停止对讲
     */
    @Override
    public void stopVoiceTalk() {
        if (mPlayer != null) {
            isTalking = false;
            callTalking(OnTalkListener.CLOSE, "结束对讲");
            mPlayer.stopAudio();
        }
    }

    /**
     * 是否正在对讲
     *
     * @return 是否正在对讲
     */
    @Override
    public boolean isTalking() {
        return isTalking;
    }

    @Override
    public boolean isPlaying() {
        return super.isPlaying() && mPlayer != null && mPlayer.isPlaying();
    }

    @Override
    public long getCurrentTime() {
        if (mPlayer != null) {
            return mPlayer.getCurrentTime();
        }
        return super.getCurrentTime();
    }

    /**
     * 获取设备能级
     */
    public void getDeviceAbility() {
        if (DEBUG)
            Logger.d(TAG, "获取设备能级");
        QlySdk.getCameraAbility(getMacByDeviceId(), new OnCameraAbilityCallback() {
            @Override
            public void onCameraAbilitySuccess(@NonNull CameraAbility cameraAbility) {
                mCameraAbility = cameraAbility;
                if (mOnCameraAbilityCallback != null) {
                    mOnCameraAbilityCallback.onCameraAbilitySuccess(cameraAbility);
                }
            }

            @Override
            public void onCameraAbilityError(String error) {
                if (mOnCameraAbilityCallback != null) {
                    mOnCameraAbilityCallback.onCameraAbilityError(error);
                }
            }
        });
    }

    /**
     * 获取设置信息
     */
    public void getCameraSettings() {
        if (DEBUG)
            Logger.d(TAG, "获取设置信息");
        QlySdk.getCameraSettings(getMacByDeviceId(), new OnCameraSettingCallback() {
            @Override
            public void onCameraSettingSuccess(@NonNull CameraSetting cameraSetting) {
                mCameraSetting = cameraSetting;
                if (mOnCameraSettingCallback != null) {
                    mOnCameraSettingCallback.onCameraSettingSuccess(cameraSetting);
                }
            }

            @Override
            public void onCameraSettingError(String error) {
                if (mOnCameraSettingCallback != null) {
                    mOnCameraSettingCallback.onCameraSettingError(error);
                }
            }
        });
    }

    @Override
    public void setPlayViewGroup(@Nullable ViewGroup viewGroup) {
        super.setPlayViewGroup(viewGroup);
        if (mPlayViewGroup != null) {
            if (mPlayer != null) {
                View playerView = mPlayer.getPlayerView();
                mPlayViewGroup.removeAllViews();
                mPlayViewGroup.addView(playerView);
            }
        }
    }

    /**
     * 设置静音
     *
     * @param mute true:静音,false:非静音
     */
    @Override
    public void setMute(boolean mute) {
        super.setMute(mute);
        setMute();
    }

    //设置静音
    protected void setMute() {
        if (mPlayer != null) {
            mPlayer.setMute(mMute);
        }
    }


    protected String getMacByDeviceId() {
        return QlySdk.getMacByDeviceId(mPlayUrl);
    }
}
